#include "system.h"

void i2c_start()
{
    SEN = 1;
    while (SEN)
    {}
}    

void i2c_stop()
{
    PEN = 1;
    while (PEN)
    {}
}    

void i2c_restart()
{
    RSEN = 1;
    while (RSEN)
    {}
}    

unsigned char i2c_write(unsigned char Val)
{
    SSPBUF = Val;
    while (RW)
    {}
    return (!ACKSTAT);
}



unsigned char i2c_read()
{
    unsigned char Tmp;
    RCEN = 1;
    while (RCEN)
    {}
    Tmp = SSPBUF;
    ACKDT = 0;
    ACKEN = 1;
    while (ACKEN)
    {}
    return(Tmp);
}    

unsigned char i2c_read_last()
{
    unsigned char Tmp;
    RCEN = 1;
    while (RCEN)
    {}
    Tmp = SSPBUF;
    ACKDT = 1;
    ACKEN = 1;
    while (ACKEN)
    {}
    return(Tmp);
}    





unsigned char i2c_read_array(unsigned char Adr, unsigned char Nom, unsigned char *Dest)
{
	unsigned char Tmp = 1;
    i2c_start();
    if(!i2c_write(0x30))
        Tmp = 0;
    if(!i2c_write(Adr))
        Tmp = 0;
    i2c_restart();
    if(!i2c_write(0x31))
        Tmp = 0;
    *Dest = 1;    
    while(--Nom)
    {
        *Dest = i2c_read();
        Dest++;
    }
    *Dest = i2c_read_last();
    i2c_stop();
    return Tmp;
}







unsigned int ReadX(unsigned char VAL)
{
    unsigned int iTmp;

    SEN = 1;
    while ((SSPCON2 & 0x1F) | RW)
    {}

    SSPBUF = 0x30;
    while ((SSPCON2 & 0x1F) | RW)
    {}

    SSPBUF = VAL;
    while ((SSPCON2 & 0x1F) | RW)
    {}


    RSEN = 1;
    while ((SSPCON2 & 0x1F) | RW)
    {}

    SSPBUF = 0x31;
    while ((SSPCON2 & 0x1F) | RW)
    {}




    /*
RCEN = 1;
while ((SSPCON2 & 0x1F) | RW)
{}
ACKDT = 0;			
ACKEN = 1;
while ((SSPCON2 & 0x1F) | RW)
{}
iTmp = SSPBUF;
*/

    RCEN = 1;
    while ((SSPCON2 & 0x1F) | RW)
    {}
    ACKDT = 1;
    ACKEN = 1;
    while ((SSPCON2 & 0x1F) | RW)
    {}

    //iTmp <<= 8;
    iTmp = SSPBUF;


    PEN = 1;
    while ((SSPCON2 & 0x1F) | RW)
    {}


    return iTmp;
}




void SaveReg(unsigned char ADDR, unsigned char VAL)
{
    SEN = 1;
    while ((SSPCON2 & 0x1F) | RW)
    {}

    SSPBUF = 0x30;
    while ((SSPCON2 & 0x1F) | RW)
    {}

    SSPBUF = ADDR;
    while ((SSPCON2 & 0x1F) | RW)
    {}

    SSPBUF = VAL;
    while ((SSPCON2 & 0x1F) | RW)
    {}

    PEN = 1;
    while ((SSPCON2 & 0x1F) | RW)
    {}

}






